import { FC, ReactNode } from 'react'
import { NavBar, TabBar } from 'antd-mobile'
import { useRouter } from 'next/router'
import {
  AppOutline,
  MessageOutline,
  UnorderedListOutline,
  UserOutline,
} from 'antd-mobile-icons'

interface PageLayoutProps {
  children: ReactNode
  showTab?: boolean
  title?: string
  onBack?: () => void
}

const PageLayout: FC<PageLayoutProps> = ({
  children,
  showTab = true,
  title,
  onBack
}) => {
  const router = useRouter()
  
  const tabs = [
    {
      key: '/',
      title: '首页',
      icon: <AppOutline />,
    },
    {
      key: '/message',
      title: '消息',
      icon: <MessageOutline />,
    },
    {
      key: '/todo',
      title: '待办',
      icon: <UnorderedListOutline />,
    },
    {
      key: '/my',
      title: '我的',
      icon: <UserOutline />,
    },
  ]

  return (
    <div className="page-layout">
      {title && (
        <div className="nav-bar">
          <NavBar onBack={onBack}>{title}</NavBar>
        </div>
      )}
      
      <div className="page-content">
        {children}
      </div>

      {showTab && (
        <div className="tab-bar">
          <TabBar activeKey={router.pathname} onChange={value => router.push(value)}>
            {tabs.map(item => (
              <TabBar.Item key={item.key} icon={item.icon} title={item.title} />
            ))}
          </TabBar>
        </div>
      )}

      <style jsx>{`
        .page-layout {
          min-height: 100vh;
          display: flex;
          flex-direction: column;
          background: #f5f5f5;
        }
        
        .nav-bar {
          position: sticky;
          top: 0;
          z-index: 1000;
          background: #fff;
          /* iOS 安全区适配 */
          padding-top: constant(safe-area-inset-top);
          padding-top: env(safe-area-inset-top);
        }
        
        .page-content {
          flex: 1;
          overflow-y: auto;
          /* 确保内容不会被底部 TabBar 遮挡 */
          padding-bottom: calc(50px + constant(safe-area-inset-bottom));
          padding-bottom: calc(50px + env(safe-area-inset-bottom));
        }
        
        .tab-bar {
          position: fixed;
          bottom: 0;
          left: 0;
          right: 0;
          background: #fff;
          /* iOS 安全区适配 */
          padding-bottom: constant(safe-area-inset-bottom);
          padding-bottom: env(safe-area-inset-bottom);
        }
        
        /* 在大屏幕上居中显示 */
        @media screen and (min-width: 600px) {
          .page-layout {
            max-width: 600px;
            margin: 0 auto;
          }
          .tab-bar {
            max-width: 600px;
            margin: 0 auto;
          }
        }
      `}</style>
    </div>
  )
}

export default PageLayout 